import * as step from '@flow-step/step-toolkit'

export const runStep = async () => {
  if(step.platform.getPlatform() === 'win') {
    step.error('This step is not supported on Windows')
    return -1
  }
  if(!process.env.variables) {
    step.error('No ENV_VARS_TO_SET found in the environment')
    return -1
  }

  const envVars = process.env.variables

  const envVarsObj = JSON.parse(envVars!) as [{ key: string, value: string}]

  for (let envVar of envVarsObj) {
    const result = await step.exec.callOutput('bash', ['-c', `echo ${envVar.value}`])
    if(result.exitCode != 0) {
      step.error(`Error while evaluating ${envVar.value}`)
      step.error(result.stderrContent)
      return -1
    }
    const evaledlValue = result.stdoutContent
    step.info(`Setting Variable ${envVar.key}=${evaledlValue}`)
    step.exportEnvVar(envVar.key, evaledlValue.trim())
    step.addOutput(`outputsToEnv.${envVar.key}=${evaledlValue.trim()}`)
  }

  return 0
}

export default runStep